package com.ilxqx.framework.system.controller.hook.inner;

import com.ilxqx.framework.schedule.util.ScheduleUtils;
import com.ilxqx.framework.system.controller.hook.PostAdd;
import com.ilxqx.framework.system.controller.hook.PostModify;
import com.ilxqx.framework.system.entity.anno.FileKey;
import com.ilxqx.framework.system.util.ReflectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * @author venus
 */
@Component
@Slf4j
@Order(0)
public class DeletionFileJobCancel implements PostAdd, PostModify {

	private static final String FILE_KEYS = "keys";

	/**
	 * 预处理
	 *
	 * @param entity 实体对象
	 * @param form   表单对象
	 * @param processingData 处理产生的数据
	 */
	@Override
	@SuppressWarnings("unchecked")
	public void handle(Object entity, Object form, Map<String, Object> processingData) {
		if (processingData.containsKey(FILE_KEYS)) {
			// 处理修改时变更的文件
			List<String> keys = (List<String>) processingData.get(FILE_KEYS);
			keys.forEach(ScheduleUtils::stopFileDeletionJob);
		} else {
			// 处理添加时变更的文件
			List<Field> fileKeyFields = ReflectionUtils.getAnnotatedFields(entity.getClass(), FileKey.class);
			fileKeyFields.forEach(field -> {
				if (!CharSequence.class.isAssignableFrom(field.getType())) {
					return;
				}
				Object value = ReflectionUtils.getFieldValue(field, entity);
				if (value != null) {
					ScheduleUtils.stopFileDeletionJob(value.toString());
				}
			});
		}
	}

}
